<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * Database class
 */
class dataBase
{
    /**
     * Connection resource.
     *
     * @var resource
     */
    private static $_con            = null;

    /**
     * dataBase class.
     *
     * @var dataBase
     */
    private static $_self           = null;

    /**
     * Constructor.
     */
    private function  __construct()
    {

    }

    /**
     * Destructor.
     */
    public function  __destruct()
    {
        mysql_close(self::$_con);
    }

    /**
     * Returns instance of this class.
     *
     * @return dataBase
     */
    public static function getInstance()
    {
        return (is_null(self::$_self) ? new dataBase() : self::$_self);
    }

    /**
     * Connect.
     *
     * @param string $host Host
     * @param string $user User
     * @param string $pass Pass
     * @param string $db Database
     * @return bool True if connected, otherwise false
     */
    public static function connect($host, $user, $pass, $db)
    {
        if (is_resource(self::$_con))
            return true;
        if ((self::$_con = mysql_connect($host, $user, $pass)) === false)
            return false;
        return (mysql_select_db($db, self::$_con) === false ? false : true);
    }

    /**
     * Function inserts new row.
     *
     * @param string $table Table name
     * @param array $fields Fields
     * @return bool
     */
    public function insert($table, $fields)
    {
        if (!is_array($fields))
            return false;

        $sql = 'INSERT INTO `' . mysql_real_escape_string($table) . '` (';
        $tmp = 'VALUES (';

        foreach ($fields as $field => $value) {
            $sql .= '`' . mysql_real_escape_string($field) . '`, ';
            $tmp .= "'" . mysql_real_escape_string($value) . "', ";
        }
        $sql = substr($sql, 0, -2) . ')' . substr($tmp, 0, -2) . ')';

        if (!mysql_query($sql, self::$_con))
                return false;
        return true;
    }

    /**
     * Function that executes query.
     *
     * @param string $query
     * @return resource | false
     */
    public function query($query)
    {
        if (!($rez = mysql_query($query, self::$_con)))
            return false;

        return $rez;
    }
}
?>
